using System;
using System.Net;
using System.Net.Sockets;

using Net.Dns;
using Net.Dns.Transport;

namespace Examples
{
  class XmmpClient
  {
    private string domainName = string.Empty;
    
    public XmmpClient(string domainName)
    {
      this.domainName = string.Concat("_xmmp-server._tcp.", domainName);
    }
        
    public void Invoke()
    {
      //prepare DNS query
      Request req = new Request();
      req.AddQuestion(new Question(this.domainName, DnsType.Srv));
      
      //Create a resolver instance with UDP transport (much faster than TCP)
      ITransport transport = new UdpTransport(Discover.GetMachineDnsServers());
      using (Resolver resolver = new Resolver(transport))
      {
        //Perform DNS lookup
        Response response = resolver.Lookup(req);
        
        //check server response
        if (response.ReturnCode != ReturnCode.Success)
          throw new Exception("Could not find a XMMP server for this domain");
          
        if (response.Answers[0].Type != DnsType.Srv)
          throw new Exception("Received incorrect resource type from the DNS server. We need a SRV record!");
          
        //Convert IRecord to a full SRV record instance
        Srv rr = response.Answers[0].record as Srv;
        
        //Resolve an IP address for the domainname. This could be a recursive query.
        //When a CNAME record is returned, a second query is performed. Standard recursive queries is set a 5 lookup.
        //When the maximum queries is reached or no results are returned, LookupIp returns the IPAddress.None field.
        IPAddress serverIP = resolver.LookupIP(rr.Hostname);
        if (serverIp == IPAddress.None)
          throw new Exception("Domainname has no A record (IP)");
                
        //Now we know where the XMMP Server is located we can make a connection with it
        IPEndpoint endpoint = new IPEndPoint(serverIp, rr.Port);
        TcpClient xmmpClient = new TcpClient();
        xmmpClient.Connect(endpoint);        
        
        //send XMMP commands
        
            
        //close connection
        xmmpClient.Close();        
      }
    }
    
    public void Main(string[] args)
    {
      //perform a XMMP (Jabber) server lookup on the domain example.org
      XmmpClient client = new XmmpClient("example.org");
      client.Invoke();
    }
  }
}
